/**
 *
 */
package com.zhuoan.im.server.service;

import com.alibaba.fastjson.JSONObject;
import com.zhuoan.im.webapp.biz.UserBiz;
import com.zhuoan.im.webapp.biz.UserLoginHistoryBiz;
import com.zhuoan.im.webapp.common.ResCodeEnum;
import com.zhuoan.im.webapp.common.exception.BizException;
import com.zhuoan.im.webapp.common.thread.ThreadPoolHelper;
import com.zhuoan.im.webapp.common.util.HttpUtil;
import com.zhuoan.im.webapp.controller.BaseController;
import com.zhuoan.im.webapp.dao.model.UserLoginHistory;
import com.zhuoan.im.webapp.dao.model.condition.UserCondition;
import org.apache.commons.lang3.StringUtils;
import org.jim.common.ImPacket;
import org.jim.common.ImSessionContext;
import org.jim.common.ImStatus;
import org.jim.common.packets.*;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.JoinGroupReqHandler;
import org.jim.server.command.handler.processor.login.LoginProcessorIntf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.ChannelContext;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author weixiang.wu
 */
@RestController
public class LoginServiceProcessor extends BaseController implements LoginProcessorIntf {

    private final static Logger logger = LoggerFactory.getLogger(LoginServiceProcessor.class);

    @Resource
    private UserBiz userBiz;

    @Resource
    private UserLoginHistoryBiz userLoginHistoryBiz;

    @Override
    public LoginRespBody doLogin(LoginReqBody loginReqBody, ChannelContext channelContext) {
        // 1、获取 [用户名密码] or [token令牌]
        String userName = loginReqBody.getLoginname();
        String password = loginReqBody.getPassword();
        String token = loginReqBody.getToken();

        //用户名+密码 不为空
        boolean byUsernameNotNull = StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password);
        //token 不为空
        boolean byTokenNotNull = StringUtils.isNotBlank(token);
        if (!byUsernameNotNull && !byTokenNotNull) {
            throw new BizException(ResCodeEnum.PARAMS_MISS.getResMessage(), ResCodeEnum.PARAMS_MISS.getResCode());
        }

        // 2、根据 [用户名密码] or [token令牌] 进行信息匹配: 返回当前用户信息、用户群组（好友）信息
        UserCondition userCondition = new UserCondition();
        User user;
        if (byUsernameNotNull) {
            userCondition.setUsername(userName);
            user = userBiz.queryUserVOByCondition(loginReqBody,userCondition,channelContext);
        } else {
            userCondition.setBlockAddr(token);
            user = userBiz.queryUserVOByCondition(loginReqBody,userCondition,channelContext);
        }

        // 3、插入登录历史表
        ThreadPoolHelper.executorService.submit(() -> insertLoginHistory(user));

        // 4、返回报文
        return new LoginRespBody(Command.COMMAND_LOGIN_RESP, ImStatus.C10007, user);

        // 5、jim对当前用户所有群组重新进行绑定
    }

    /**
     * 发送加入群组通知
     *
     * @param channelContext
     */
    @Override
    public void onSuccess(ChannelContext channelContext) {
        logger.info("登录成功回调方法");
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        User user = imSessionContext.getClient().getUser();
        if (user.getGroups() != null) {
            //发送加入群组通知
            for (Group group : user.getGroups()) {
                ImPacket groupPacket = new ImPacket(Command.COMMAND_JOIN_GROUP_REQ, JsonKit.toJsonBytes(group));
                try {
                    JoinGroupReqHandler joinGroupReqHandler = CommandManager.getCommand(Command.COMMAND_JOIN_GROUP_REQ, JoinGroupReqHandler.class);
                    joinGroupReqHandler.joinGroupNotify(groupPacket, channelContext);

                    // 发送到群组
                    // ImAio.sendToGroup(groupId, joinGroupNotifyrespPacket);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean isProtocol(ChannelContext channelContext) {
        return true;
    }

    @Override
    public String name() {
        return "default";
    }

    private void insertLoginHistory(User user) {
        UserLoginHistory userLoginHistory = new UserLoginHistory();
        userLoginHistory.setGmtCreate(new Date());
        String s = HttpUtil.sendPost("http://pv.sohu.com/cityjson");
        JSONObject jsonObject = JSONObject.parseObject(s.substring(s.indexOf("{"), s.indexOf("}") + 1));
        userLoginHistory.setUserId(Long.valueOf(user.getId()));
        userLoginHistory.setIp(String.valueOf(jsonObject.get("cip")));
        userLoginHistory.setRegion(String.valueOf(jsonObject.get("cname")));
        try {
            userLoginHistoryBiz.insertSelective(userLoginHistory);
        } catch (Exception e) {
            logger.error("用户id={}登录信息插入失败:{}", user.getId(), e.getMessage());
        }
    }


}
